package com.cn.aam.checaiduo.base.web;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.http.SslError;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;

import com.baoyz.widget.PullRefreshLayout;
import com.cn.aam.checaiduo.AppData;
import com.cn.aam.checaiduo.BuildConfig;
import com.cn.aam.checaiduo.Const;
import com.cn.aam.checaiduo.R;
import com.cn.aam.checaiduo.backend.cookie.CookieCenter;
import com.cn.aam.checaiduo.base.BaseActivity;
import com.cn.aam.checaiduo.base.ToolBarManager;
import com.cn.aam.checaiduo.utils.MyViewsUtils;
import com.cn.aam.checaiduo.widget.ObservableWebView;
import com.cn.aam.checaiduo.widget.WMToast;
import com.orhanobut.logger.Logger;

import java.lang.reflect.Field;
import java.util.HashMap;

import butterknife.BindView;

/**
 * 基本web页面
 */
public abstract class BaseWebActiivity extends BaseActivity {
    @BindView(R.id.lin_background)
    LinearLayout linBackground;
    @BindView(R.id.id_webview)
    protected ObservableWebView mWebView;//自定义的webView，可以获取他的滑动情况
    @BindView(R.id.id_swipe)
    PullRefreshLayout mRefreshLayout;


    protected WebViewHelper.GOTO aGotoFlag = WebViewHelper.GOTO.OTHER;

    private WebAppInterface webAppInterface;
    private float currentScale;

    protected String targetUrl;
    protected String targetTitle;

    public String getTargetUrl() {
        return getIntent().getStringExtra(Const.TARGET_URL);
    }

    public String getTargetTitle() {
        return getIntent().getStringExtra(Const.TARGET_TITLE);
    }

    @Override
    protected int layoutId() {
        return R.layout.activity_web_normal;
    }

    @Override
    protected void onGenerate() {
        targetTitle = getTargetTitle();
        targetUrl = getTargetUrl();
    }

    @Override
    protected void initView() {
        MyViewsUtils.hideAllViews(mWebView);
        initToolBar();
        initRefreshLayout();
        initWebViews();
    }

    protected void initToolBar() {
        ToolBarManager.with(this, WMContent)
                .setBackgroundColor(R.color.toolbar_bg_grey)
                .setLeftMenuIconRes(R.drawable.ic_nav_arrow_back)
                .setLeftMenuIconClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        onBackPressed();
                    }
                })
                .setTitle(targetTitle)
                .setTitleColor(R.color.black_normal)
//                .setLeftMenuTextContent("关闭")
//                .setLeftMenuTextColor(R.color.black_normal)
//                .setLeftMenuTextClick(new ToolBarManager.OnMenuTextClickListener() {
//                    @Override
//                    public void onMenuTextClick() {
//                        finish();
//                    }
//                })
                .fitSystemWindow(this);
    }

    private void initRefreshLayout() {
        //下拉刷新控件的配色
        mRefreshLayout.setColorSchemeColors(mContext.getResources().getColor(R.color.colorPrimary));
        beginRefreshAnimation();
    }

    protected void initWebViews() {
        String gotoFlag = getIntent().getStringExtra("gotoFlag");
        if (TextUtils.equals("MEFRAGMENT", gotoFlag)) {
            aGotoFlag = WebViewHelper.GOTO.MEFRAGMENT;
        } else {
            aGotoFlag = WebViewHelper.GOTO.OTHER;
        }

        //sync app cookie
        CookieCenter.getInstance().synCookies(mContext, targetUrl);

        WebSettings settings = mWebView.getSettings();//
        settings.setJavaScriptEnabled(true);//支持javaScript
        settings.setUserAgentString(settings.getUserAgentString() + "CheCaiDuo");
        //settings.setAllowFileAccess(true);//允许访问文件数据
        //settings.setBuiltInZoomControls(true);//设置支持缩放
        //settings.setDatabaseEnabled(true);
        settings.setAppCacheEnabled(true);
        settings.setBlockNetworkImage(false);
        settings.setDomStorageEnabled(true);//开启DOM缓存，关闭的话H5自身的一些操作是无效的
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        settings.setLoadsImagesAutomatically(true);//在页面装载完成之后再去加载图片。
        settings.setAllowUniversalAccessFromFileURLs(true);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);
        //检查是否有网络
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();
        if (info != null && info.isAvailable()) {
            settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        } else {
            settings.setCacheMode(WebSettings.LOAD_CACHE_ONLY);//不使用网络，只加载缓存
        }

        mWebView.requestFocus();
        mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);//滚动条样式
        webAppInterface = new WebAppInterface(mContext);
        mWebView.addJavascriptInterface(webAppInterface, "JSBridge");
        mWebView.setWebViewClient(new WebViewClient() {


            /**
             * @param view
             * @param url
             * @return boolean
             * @description 希望点击链接由自己处理
             * @remark
             *
             * return true; webview处理url是根据程序来执行的。
             * return false; webview处理url是在webview内部执行。
             */
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                Logger.e("shouldOverrideUrlLoading  " + "url=" + url);
                WebViewHelper.getInstance().setGotoFlag(aGotoFlag).dispatchUrl(url, view);
                OverrideUrlLoading(view, url);//供子类使用
                return false;
            }


            //js执行完在执行此方法
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                MyViewsUtils.showAllViews(mWebView);
                endRefreshAnimation();
            }

            @Override
            public void onScaleChanged(WebView view, float oldScale, float newScale) {
                super.onScaleChanged(view, oldScale, newScale);
                currentScale = newScale;
            }


            //webView默认是不处理https请求的，页面显示空白
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                //super.onReceivedSslError(view, handler, error);
                handler.proceed();//表示等待证书响应
                // handler.cancel();//表示挂起连接，为默认方式
                // handler.handleMessage(null); } });//可做其他处理
            }

        });
        //设置了Alert才会弹出，重新onJsAlert（）方法return true可以自定义处理信息
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                return super.onJsAlert(view, url, message, result);
            }

        });
        //check url null
        if (TextUtils.isEmpty(targetUrl)) {
            WMToast.normal("url不能为空");
            onBackPressed();
            return;
        }
        loadEverThing(targetUrl);

    }

    protected void loadEverThing(String str) {
        //mWebView.loadUrl("file:///android_asset/XX.html");//本地文件存放在：assets文件中

        HashMap<String, String> map = new HashMap<String, String>();
        map.put("token", AppData.getToken());
        //check url type and load
        if (str.startsWith("http:") || str.startsWith("https:")) {
            mWebView.loadUrl(str, map);
        } else {
            mWebView.loadData(str, "text/html", "utf-8");
        }
        Logger.d("初始网页=" + str);
    }

    protected void OverrideUrlLoading(WebView view, String url) {

    }


    //开始刷新动画
    protected void beginRefreshAnimation() {
        mRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                mRefreshLayout.setRefreshing(true);
            }
        });
    }

    //结束刷新动画
    protected void endRefreshAnimation() {
        if (mRefreshLayout != null)
            mRefreshLayout.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (mRefreshLayout == null) {
                        return;
                    }

                    mRefreshLayout.setEnabled(false);
                    mRefreshLayout.setRefreshing(false);

                }
            }, 1000);
    }


    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
            return;
        }
        super.onBackPressed();
    }

    //防止后台无法释放js导致耗电
    @Override
    protected void onResume() {
        super.onResume();
        mWebView.getSettings().setJavaScriptEnabled(true);
    }


    @Override
    protected void onDestroy() {
        mWebView.setWebViewClient(null);
        mWebView.getSettings().setJavaScriptEnabled(false);
        mWebView.stopLoading();
        releaseAllWebViewCallback();
        super.onDestroy();
    }

    //释放访内存
    public void releaseAllWebViewCallback() {
        try {
            Field sConfigCallback = Class.forName("android.webkit.BrowserFrame").getDeclaredField("sConfigCallback");
            if (sConfigCallback != null) {
                sConfigCallback.setAccessible(true);
                sConfigCallback.set(null, null);
            }
        } catch (NoSuchFieldException e) {
            if (BuildConfig.DEBUG) {
                e.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            if (BuildConfig.DEBUG) {
                e.printStackTrace();
            }
        } catch (IllegalAccessException e) {
            if (BuildConfig.DEBUG) {
                e.printStackTrace();
            }
        }

    }


    //js调用android的方法
    class WebAppInterface {
        private Context mContext;

        /**
         * Instantiate the interface and set the context
         */
        WebAppInterface(Context c) {
            mContext = c;
        }


        //样例接口
        @JavascriptInterface
        public void clickTune(String id) {

        }
    }


    /**
     * @param jsStr js字符串
     * @description 注入JS至WebView
     */
    protected void injectJavaScripToWebView(String jsStr) {
        String rs = "javascript:" + jsStr;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            mWebView.evaluateJavascript(jsStr, null);
        } else {
            mWebView.loadUrl(rs);
        }
    }


}
